package utils {
	import flash.net.SharedObject;
	
	import mx.collections.ArrayList;
	
	import datas.LinkData;
	
	public class SharedObjectsHelper {
		
		public function SharedObjectsHelper() {
		}
		
		public static function getSelectedCountry():String {
			var obj:SharedObject = SharedObject.getLocal("Preferenses", "/");
			if (obj.data.hasOwnProperty("selectedCountry")) {
				return String(obj.data.selectedCountry);
			}
			return null;
		}
		
		public static function saveSelectedCountry(value:String):void {
			var obj:SharedObject = SharedObject.getLocal("Preferenses", "/");
			obj.data.selectedCountry = value;
			obj.flush();
		}
		
		public static function getLatestLinks():Array {
			var obj:SharedObject = SharedObject.getLocal("Preferenses", "/");
			if (obj.data.hasOwnProperty("latestLinks")) {
				return obj.data.latestLinks;
			}
			return [];
		}
		
		public static function addLatestLink(link:LinkData):void {
			var obj:SharedObject = SharedObject.getLocal("Preferenses", "/");
			if (obj.data.hasOwnProperty("latestLinks")) {
				var al:ArrayList = new ArrayList(obj.data.latestLinks);
				if (findLatestLink(al, link.href, link.name)) {
					return ;
				}
				al.addItemAt(link, 0);
				if (al.length > 50) {
					al.removeItemAt(50);
				}
			} else {
				var arr:Array = [];
				arr.push(link);
				obj.data.latestLinks = arr;
			}
			obj.flush();
		}
		
		public static function findLatestLink(al:ArrayList, href:String, name:String):Object {
			for each(var l:Object in al.source) {
				if (l.href == href) {
					return l;
				}
				if (l.name == name) {
					var n:String = l.name as String;
					if (n.length > 5) {
						return l;
					}
				}
			}
			return null;
		}
		
		public static function clearRecentLinks():void {
			var obj:SharedObject = SharedObject.getLocal("Preferenses", "/");
			obj.data.latestLinks = [];
			obj.flush();
		}
	}
}

